package com.cskaoyan.advice;

import com.cskaoyan.util.MyBatisUtil;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class TransactionAdvice implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        // get target object
        Object aThis = methodInvocation.getThis();
        Field[] declaredFields = aThis.getClass().getDeclaredFields();
        SqlSession sqlSession = null;
        for (Field declaredField : declaredFields) {
            //是否是Mapper成员变量
            String name = declaredField.getName();
            if (name.endsWith("Mapper")) {
                sqlSession = MyBatisUtil.getSqlSession();
                Class<?> type = declaredField.getType();
                Object mapper = sqlSession.getMapper(type);//mapper代理对象
                declaredField.setAccessible(true);
                declaredField.set(aThis,mapper);
            }
        }
        Object proceed = methodInvocation.proceed();
        if (sqlSession != null) {
            sqlSession.commit();
            sqlSession.close();
        }
        return proceed;
    }
}
